const bcrypt = require('bcryptjs');

const restrict = require(__util + "/restrict")
const errcode = require(__util + "/errcode")

const models = require(__base + "/models");

module.exports = async (req, res, next) => {
  const { username, password } = req.body

  const checkRet = await checkAccount(username, password)
  if (checkRet.errcode) {
    res.json(checkRet)
  } else {
    // 若验证通过, 签发token
    const token = await restrict.signToken(checkRet.data)
    res.json(
      errcode.SUCCESS({
        token: token
      })
    );
  }
};

// 检查数据库用户账号密码是否正确
const checkAccount = async (username, password) => {
  // 先判断username是否为空, 在判断账号是否存在, 最后判断密码是否正确
  if (username) {
    const accountInfo = await models.Account.findOne({
      where: {
        username: username
      }
    })
    if (accountInfo) {
      const checkPwdRet = await bcrypt.compareSync(password, `${accountInfo.hash}`)
      if (checkPwdRet) {
        return errcode.SUCCESS({
          id: accountInfo.id,
          username: accountInfo.username
        })
      } else {
        return errcode.PASSWORD_INVALID
      }
    } else {
      return errcode.USERNAME_NOT_EXIST
    }
  } else {
    return errcode.USERNAME_EMPTY
  }
}